package com.itheima.edu.info.manajer.dao;

import com.itheima.edu.info.manajer.domain.Student;


public class StudentDao implements BaseStudentDao {
    //1创建学生对象数组
    private static Student[] stus = new Student[5];
    //静态代码块,本代码块用于测试
    static {
        Student student1 = new Student("001","张三","23","1993-3-3");
        Student student2 = new Student("002","李四","24","1994-4-4");

        stus[0]=student1;
        stus[2]=student2;
    }

    public boolean addStudent(Student stu) {
        //2添加学生到数组
        //2.1定义变量index为-1,假设数组已经存满,没有null元素
        int index = -1;
        //2.2遍历数组取出每一个元素,判断是否是null
        for (int i = 0; i < stus.length; i++) {
            Student student = stus[i];
            if (student == null) {
                index = i;
                //2.3如果是null,让index变量记录当前索引位置,并使用break结束循环遍历
                break;
            }
        }

        //3返回是否添加成功的boolean类型状态
        if (index == -1) {
            //装满了
            return false;
        } else {
            //没有装满,正常添加,返回true
            stus[index] = stu;
            return true;
        }
    }


    public Student[] findAllStudent() {
        return stus;
    }

    public void deleteStudentById(String delId) {
        //1查找id在容器中所在的索引位置
        int index = getIndex(delId);
        //2将该索引位置,使用nullyuans进行覆盖
        stus[index] = null;
    }

    public int getIndex(String id) {
        int index = -1;
        for (int i = 0; i < stus.length; i++) {
            Student stu = stus[i];
            if (stus != null && stu.getId().equals(id)) {
                index = i;
                break;
            }
        }
        return index;
    }

    public void updateStudent(String updateId, Student newStu) {
        //1查找updateId,在容器中的索引位置
        int index = getIndex(updateId);
        //2经该索引,使用新的学生对象替换
        stus[index] = newStu;
    }
}
